import 'dart:io';

import 'package:dio/dio.dart';
import 'package:loxen/utils/file_util.dart';
import 'dio_setting.dart';

//封装http  POST GET请求
class HttpUtil {

  static Future<String> downLoad(bool isAndroid, String url, String path,
      Function(int count, int total) onReceiveProgress) async {
    Directory directory = await FileUtil.getPath();
    if (directory != null) {
      await BaseNetWork.instance.dio.download(url, path, onReceiveProgress: onReceiveProgress);
      return path;
    } else {
      return null;
    }
  }

  static Future<Response> delete(String url, {dynamic params, dynamic queryParameters}) async {
    try {
      Response response = await BaseNetWork.instance.dio
          .delete(url, queryParameters: queryParameters, data: params);
      return response;
    } catch (ex) {
      throw ServiceException(ex);
    }
  }

  static Future<Response> get(String url, {dynamic params}) async {
    try {
      Response response = await BaseNetWork.instance.dio.get(url, queryParameters: params);
      return response;
    } catch (ex) {
      if (ex is DioError) {
        throw ServiceException(ex);
      } else {
        throw ex;
      }
    }
  }

  static Future<Response> put(String url, {dynamic params, dynamic queryParameters}) async {
    try {
      Response response =
          await BaseNetWork.instance.dio.put(url, queryParameters: queryParameters, data: params);
      return response;
    } catch (ex) {
      if (ex is DioError) {
        throw ServiceException(ex);
      } else {
        throw ex;
      }
    }
  }

  static Future<Response> post(String url, dynamic params) async {
    try {
      Response response = await BaseNetWork.instance.dio.post(url, data: params);
      return response;
    } catch (ex) {
      if (ex is DioError) {
        throw ServiceException(ex);
      } else {
        throw ex;
      }
    }
  }
}

//自定服务器异常义异常
class ServiceException implements Exception {
  int statusCode = -100;
  String statusMessage = '未知异常';
  int code = -100;
  String message = '未知异常';
  Object userMessage;
  dynamic data;

  String getErrorMsg(String name) {
    return data['data'][name][0].toString();
  }

  ServiceException(DioError error) {
    print(error.request.path);
    if (error.response != null) {
      statusCode = error.response.statusCode;
      statusMessage = error.response.statusMessage;
      data = error.response.data;
      try {
        code = error.response.data['code'];
        message = error.response.data['data'].toString();
        StringBuffer buffer = StringBuffer();
        buffer.writeln('Status Code:$statusCode');
        buffer.writeln('Status Message:$statusMessage');
        buffer.writeln('Code:$code');
        buffer.writeln('Message:$message');
        userMessage = error.response.data['data'];
        message = buffer.toString();
      } catch (e) {
        print(e);
      }
    }
  }

  @override
  String toString() {
    return message;
  }
}
